/*
 * Adara WebCam TimeLapse capture software.
 * Copyright (C) 2012 AdaraProjectTeam
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package adara.config;

import java.io.File;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;

import adara.commons.ResourceDiscovery;

/**
 * A configuration utility. Reads the adara.properties file located in classpath
 * and provide the access to configured parameters.
 * @author Andrei Ermicioi (aka erani) <andrei.ermicioi@gmail.com>
 *
 */
public class ConfigurationUtils {
	
	private static final Logger logger = 
			Logger.getLogger(ConfigurationUtils.class);
	
	private static Configuration config = null;
	
	public static Configuration getConfiguration() 
			throws ConfigurationException {
		
		if (config == null) {
			synchronized (ConfigurationUtils.class) {
				if (config == null) {
					config = loadConfiguration();
					ConfigurationValidator.validate(config);
				}
			}
		}
		
		return config;
	}
	
	private static Configuration loadConfiguration() 
			throws ConfigurationException {
		
		if (logger.isTraceEnabled())
			logger.trace("Loading configuration");
		
		File configfile = new File(
				ResourceDiscovery.getClasspathResource("adara.properties"));
			
		if (logger.isTraceEnabled()) 
			logger.trace("Configuration location: " + configfile.getAbsolutePath());
		
		if (!configfile.exists()) {
			throw new ConfigurationException("The configuration file is missing");
		}
		
		return new PropertiesConfiguration(configfile);
	}
}
